import json
import time
import uuid
import struct


import asyncio
import websockets


running = True

async def start():
    uri = 'ws://127.0.0.1:9000/ws'
    async with websockets.connect(uri) as websocket:
        print("start")
        await asyncio.gather(*[
                send_messages(websocket),
#                 recv_messages(websocket)
            ])

async def recv_messages(ws):
    while running:
        recv_data = await ws.recv()
        print('<<< %s' % recv_data)
    print("recv end")

def make_msg(command, imei):
    userId = '10001'

    # 数据转换为 bytes
    imei_bytes = imei.encode('utf-8')
    imei_length = len(imei_bytes)
    name_bytes = json.dumps({"userId": userId}).encode('utf-8')
    body_length = len(name_bytes)

    # 基础数据
#     command = 9000
    version = 1
    clientType = 4
    messageType = 0x0
    appId = 10000

    # 打包整数为大端序的二进制格式，并包括 imei_length 和 body_length
    header_format = '>5i2I'  # 5个int类型的基础数据，加上2个unsigned int类型的长度数据
    packed_header = struct.pack(header_format, command, version, clientType, messageType, appId, imei_length, body_length)

    # 构建最终的二进制消息
    return packed_header + imei_bytes + name_bytes

async def send_messages(ws):
#     await ten_msg(ws)
    imei = str(uuid.uuid1())
    # login
#     final_message = make_msg(9000, imei)
#     await ws.send(final_message)
#     await asyncio.sleep(10)
    # logout
#     final_message = make_msg(9003, imei)
#     await ws.send(final_message)


    final_message = make_msg(90031, imei)
    await ws.send(final_message)

async def ten_msg(ws):
    imei = str(uuid.uuid1())
    userId = '10001'

    # 数据转换为 bytes
    imei_bytes = imei.encode('utf-8')
    imei_length = len(imei_bytes)
    name_bytes = json.dumps({"userId": userId}).encode('utf-8')
    body_length = len(name_bytes)

    # 基础数据
    command = 9000
    version = 1
    clientType = 4
    messageType = 0x0
    appId = 10000

    # 打包整数为大端序的二进制格式，并包括 imei_length 和 body_length
    header_format = '>5i2I'  # 5个int类型的基础数据，加上2个unsigned int类型的长度数据
    packed_header = struct.pack(header_format, command, version, clientType, messageType, appId, imei_length, body_length)

    # 构建最终的二进制消息
    final_message = packed_header + imei_bytes + name_bytes
    # 发送消息
    for _ in range(10):
        await ws.send(final_message)
        print('>>> %s' % final_message)
        await asyncio.sleep(1)  # 间隔1秒发送，避免过快
    running = False
    print("send end")

if __name__ == "__main__":
    asyncio.run(start())
